package com.itcast.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.yygh.cmn.listener.DictListener;
import com.itcast.yygh.cmn.mapper.DictMapper;
import com.itcast.yygh.cmn.service.DictService;
import com.itcast.yygh.model.model.cmn.Dict;
import com.itcast.yygh.model.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 数据字典服务模块实现类
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private DictListener dictListener;

    //@Cacheable(value = "dict")
    @Override
    public List<Dict> findChildData(Long id) {
        //1.需要根据id查询字段数据
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        //设置查询条件
        queryWrapper.eq("parent_id",id);
        //查询数据
        List<Dict> dicts = baseMapper.selectList(queryWrapper);
        //2.需要循环查询到的数据,根据数据的id查询
        for (Dict dict:dicts) {
            Long dictId = dict.getId();
            //判断当前父节点的数据是否有子节点
            //3.判断查询到的数据的条数是否大于0 如果大于0说明有子数据,就把
            //dict对象中hasChildren设置为true
            boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }

        return dicts;
    }
    //数据字典导出功能实现
    @Override
    public void exportData(HttpServletResponse response) {
        try{
            //1.需要设置响应头中的信息  contentType  响应文件的类型   charsetEncoding设置编码  Header 响应头
            response.setContentType("application/vnd.ms-excel");
            //设置编码
            response.setCharacterEncoding("UTF-8");
            //生成文件名称
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            //设置头信息
            response.setHeader("Content-disposition","attachment;filename="+ fileName + ".xlsx");
            //2.需要查询数据库中所有的数据
            List<Dict> dicts = baseMapper.selectList(null);
            //创建一个新的集合
            List<DictEeVo> dictEeVos = new ArrayList<>(dicts.size());
            //3.将dict中属性字段拷贝到dictEevo中
            for (Dict dict:dicts) {
                DictEeVo dictEeVo = new DictEeVo();
                //方法中需要两个参数:1.被拷贝的对象  2.要拷贝到的对象
                BeanUtils.copyProperties(dict,dictEeVo);
                dictEeVos.add(dictEeVo);
            }
            //4.执行导出命令
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("数据字典").doWrite(dictEeVos);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void importData(MultipartFile file) {
        try{
            EasyExcel.read(file.getInputStream(),DictEeVo.class,dictListener).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        //1.根据value来进行查询,如果查询出来的数据是一个对象,直接使用,否则就根据两个字段查询
        if(StringUtils.isEmpty(parentDictCode)){
            //根据value值进行查询
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(queryWrapper);
            if(!Objects.isNull(dict)){
                return dict.getName();
            }
        }else{
            //根据parentDictCode查询数据中是否有这个对象
            Dict parentDict = this.getDictByDictCode(parentDictCode);
            if(Objects.isNull(parentDict)){
                return null;
            }
            //根据parentId+value进行查询
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id",parentDict.getId());
            queryWrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(queryWrapper);
            if(!Objects.isNull(dict)){
                return dict.getName();
            }

        }
        return "";
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //先根据dictCode查询字典数据
        Dict dict = this.getDictByDictCode(dictCode);
        if(Objects.isNull(dict)){
            return null;
        }
        //查询字典下级中的数据
        List<Dict> dicts = this.findChildData(dict.getId());
        return dicts;
    }

    //根据父类dict_code查询字典数据
    private Dict getDictByDictCode(String parentDictCode) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code",parentDictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);
        return dict;
    }

    //判断当前父节点是否有子节点
    private boolean isChildren(Long id){
        //1.构建查询条件
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        //2.根据parent_id是否能查询出来数据
        queryWrapper.eq("parent_id",id);
        //3.判断查询出来的数据条数是否大于0  如果大于0就返回true否则就返回false
        Integer count = baseMapper.selectCount(queryWrapper);
        return count>0;
    }
}
